package com.auth.gateway.service;

import com.auth.gateway.model.LoginSession;
import com.auth.gateway.model.SystemLoginConfig;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseCookie;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class FormLoginStrategy implements LoginStrategy {

    private final WebClient webClient = WebClient.create();

    @Override
    public Mono<LoginSession> login(String userId, SystemLoginConfig config) {
        return webClient.post()
                .uri(config.getLoginUrl())
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .body(BodyInserters.fromFormData(config.getUsernameParam(), userId)
                        .with(config.getPasswordParam(), config.getStaticPassword()))
                .exchangeToMono(resp -> {
                    List<ResponseCookie> cookies = resp.cookies().get("JSESSIONID");
                    LoginSession session = new LoginSession();
                    session.setSystemCode("legacy-a");
                    if (cookies != null) {
                        cookies.forEach(cookie -> session.getCookies().put(cookie.getName(), cookie.getValue()));
                    }
                    return Mono.just(session);
                });
    }
}